package com.simple.mybaits.simplemybatis.ds.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.simple.mybaits.simplemybatis.ds.DataSourceFacotry;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @author :  zxj
 * @package :  com.simple.mybaits.simplemybatis.ds
 * @date :  2018/5/21
 * @description : jdbc实现
 */
public class JdbcDataSourceFactory implements DataSourceFacotry {

    /**
     * url参数
     */
    private static final String DB_URL = "database.url";
    /**
     * 用户名
     */
    private static final String USER = "database.user";
    /**
     * 密码
     */
    private static final String pwd = "database.password";
    /**
     * driver
     */
    private static final String driver = "db.driver";

    /**
     * 数据源
     */
    private DruidDataSource dataSource;

    @Override
    public void setProperties(Properties props) {
        dataSource = new DruidDataSource();
        //设置连接参数
        dataSource.setUrl(props.getProperty(DB_URL));
        dataSource.setDriverClassName(props.getProperty(driver));
        dataSource.setUsername(props.getProperty(USER));
        dataSource.setPassword(props.getProperty(pwd));
        //配置初始化大小、最小、最大
        dataSource.setInitialSize(1);
        dataSource.setMinIdle(1);
        dataSource.setMaxActive(20);
        //连接泄漏监测
        dataSource.setRemoveAbandoned(true);
        dataSource.setRemoveAbandonedTimeout(30);
        //配置获取连接等待超时的时间
        dataSource.setMaxWait(20000);
        //配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
        dataSource.setTimeBetweenEvictionRunsMillis(20000);
        //防止过期
        dataSource.setValidationQuery("SELECT 'x'");
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnBorrow(true);
    }

    @Override
    public DataSource getDataSource() {
        return dataSource;
    }
}
